package com.joker.controller;
import com.alibaba.fastjson.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


import com.joker.pojo.*;
import com.joker.service.UserMessageImpl;
import com.joker.socketservice.WebsocketGroupMessage;
import com.joker.socketservice.WebsocketUserMessage;
import com.joker.test.DBtest;
import com.joker.utily.MYbatisutil;
import com.joker.utily.TimeUtil;
import com.sun.xml.internal.ws.api.message.ExceptionHasMessage;
import org.springframework.web.bind.annotation.CrossOrigin;

@CrossOrigin
@ServerEndpoint("/webSocket/{username}")

public class WebsocketController {
//    private static UserMessageImpl userMessageService;
//    private static org.springframework.beans.factory.BeanFactory beanFactory;
//    @Autowired
//    @Qualifier("BookServiceImpl")
//    public BookService bookService;
    //手动注入service层
//    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//
//    UserMessageService userMessageService = (UserMessageService)ac.getBean("UserMessageServiceImpl");
//    @Autowired
//    public void setUserMessageImpl(UserMessageImpl userMessageMapper){
//        WebsocketController.userMessageService=userMessageMapper;
//    }
    private static int onlineCount = 0;
    private static Map<String, WebsocketController> clients = new ConcurrentHashMap<String, WebsocketController>();
    //private static Message data;
    private Session session;
    private Integer userid;

    @OnOpen
    public int onOpen(@PathParam("username") String username, Session session) throws IOException {
        //确保同一个id不会重复登陆
        System.out.println("当前人数:"+onlineCount);
        for (String name:clients.keySet()
             ) {
            System.out.println("已经登陆的人"+name);

        }
        for (String name:clients.keySet()) {
            if(name.equals(username)){
                System.out.println("重复登录");
                return 0;
            }
        }
        this.userid = Integer.parseInt(username);
        this.session = session;
        addOnlineCount();
        clients.put(username, this);
        System.out.println(username+"用户上线");
        System.out.println("当前人数:"+onlineCount);
        return 0;
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(userid.toString());
        subOnlineCount();
        System.out.println("有用户下线该用户是"+userid);
        System.out.println("当前人数"+onlineCount);
    }

    @OnMessage
    public void onMessage(String message) throws IOException, SQLException, ClassNotFoundException {
//        System.out.println("发出了消息");
        System.out.println(message.getBytes());
        //添加判断逻辑，对发群组还是发个人。
        JSONObject json=JSONObject.parseObject(message);
        System.out.println("输出message"+json.toJSONString());
        Message data=JSON.parseObject(json.toJSONString(),Message.class);
        System.out.println("data是"+data);
        //判断是不是群发
        if(data.getGroupid()!=null && !data.getGroupid().equals("")) {
            //groupid不为空
            System.out.println("群发");
            //给当前在线，同时还是这个群的人发消息，然后入库
            Group groups= MYbatisutil.selectid(Integer.parseInt(data.getGroupid()));
            ArrayList<Group_Member> groupmember= (ArrayList<Group_Member>) groups.getGroup_members();
            Iterator iterator=groupmember.iterator();
            //调用自定义的orm层
            WebsocketGroupMessage websocketGroupMessage=new WebsocketGroupMessage();
            Group_Message group_message=new Group_Message();
            group_message.setGroupid(Integer.parseInt(data.getGroupid()));
            group_message.setCreateuserid(data.getMyid());
            group_message.setData(data.getMessage());
            group_message.setDate(TimeUtil.nowdate());
            websocketGroupMessage.addGroupMessage(group_message);
            while (iterator.hasNext()){
                Group_Member groupMember= (Group_Member) iterator.next();
                System.out.println("群成员"+groupMember.getUserid()+"------------");
                //遍历当前在线的用户
                for (WebsocketController item : clients.values()) {

                    System.out.println("在线的用户"+item.userid);
                    if (item.userid.toString().equals(groupMember.getUserid().toString()) ) {
                        item.session.getAsyncRemote().sendText(message);
                        System.out.println("执行了群送");
                    }

                }

            }
            //通过群的groupid查到群成员id,对比在线的userid。发送消息，这里应该用什么数据结构。
            //从群创建开始，就有一个集合对象被创建，里边存的是群的用户id,发送消息时，遍历当前的集合和在线的用户，如果满足userid一致就发送。


        }
        else {
            //私发消息
            System.out.println(this);
            System.out.println("用户id为"+data.getMyid()+"对用户id为"+data.getUserid()+"发起对话");
            sendMessageTo(data.getMessage(),data.getUserid().toString());
            User_Message usermessage=new User_Message();
            usermessage.setUserid(data.getMyid());
            System.out.println("发送者的id"+data.getMyid());
            //data.setMessage(new String (data.getMessage().getBytes("GB2312"),"UTF-8"));
            String ss=DBtest.getEncoding(data.getMessage());

            System.out.println("java字符集"+ss);
            usermessage.setBecalluserid(data.getUserid());
            usermessage.setData(data.getMessage());
            usermessage.setDate(TimeUtil.nowdate());
            System.out.println(usermessage);
            try {

                WebsocketUserMessage websocketUserMessage=new WebsocketUserMessage();
                websocketUserMessage.addUserMessage(usermessage);
//              addusermessage addusermessage=new addusermessage();
//              addusermessage.jdbcadd(usermessage.getUserid(),usermessage.getBecalluserid(),usermessage.getData(),usermessage.getDate());
                //ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
                // UserMessageImpl userMessageImpl= (UserMessageImpl)ContextLoader.getCurrentWebApplicationContext().getBean("UserMessageImpl");
                // System.out.println(userMessageImpl);
                //UserMessageService userMessage = (UserMessageService)ac.getBean("UserMessageServiceImpl");
//                userMessage.addUsermessage(usermessage);
//                AddUserMessage.addmessage(usermessage);
            }
            catch (Exception e){
                e.printStackTrace();
            }

        }





    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMessageTo(String message, String To) throws IOException {

        for (WebsocketController item : clients.values()) {

            if (item.userid.toString().equals(To) ) {
                item.session.getAsyncRemote().sendText(message);
                System.out.println("执行了发送");
            }
        }
        //遍历在线用户
        for (WebsocketController item:clients.values()) {
            System.out.println("在线用户"+item);
            System.out.println("用户名"+item.userid);
        }
    }

    public void sendMessageAll(String message) throws IOException {

        for (WebsocketController item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        WebsocketController.onlineCount++;
    }
    public static synchronized void subOnlineCount() {
        WebsocketController.onlineCount--;
    }

    public static synchronized Map<String, WebsocketController> getClients() {
        return clients;
    }


}